% created by tyy on 2023/11/07
function [x_out,f_out,cnt,time,code] = f_secant_method(equation,range,tolerance,maxIteration)
% 割线法
syms x;
% iteration parameters
a = range(1); % left point
b = range(2); % right point

% Newton Iterative Method
k_x = zeros(maxIteration,1);
f_x = zeros(maxIteration,1);
tic;
x_1 = a;
x_2 = b;
f_x1 = subs(equation,x,x_1);
f_x2 = subs(equation,x,x_2);
for i = 1:maxIteration
    k_x(i,1) = (f_x2-f_x1) / (x_2-x_1); % the deriative on xi
    f_x(i,1) = f_x2; 
    delta  = -f_x(i,1) / k_x(i,1);
    x_next = x_2 + delta;
    x_1 = x_2; % 更新
    x_2 = x_next;
    f_x1 = f_x2;
    f_x2 = subs(equation,x,x_2);
    % x_new = x_value - subs(equation,x,x_value)/k_x(i,1);
    if abs(double(f_x2)) < tolerance
        code = 0;
        break;
    end
end
time = toc;

if (i >= maxIteration) 
    code = -1; 
end
x_out = x_2;
f_out = subs(equation,x,x_out);
cnt = i;